
package com.shuigu.ai.langgraph4j.tools;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.shuigu.ai.langgraph4j.model.ImageCategoryEnum;
import com.shuigu.ai.langgraph4j.model.ImageResource;
import com.shuigu.common.utils.oss.AliyunOss;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.List;

/**
 * docker 部署 kroki、kroki-mermaid
 */
@Slf4j
@Component
public class KrokiMermaidDiagramTool {

    @Resource
    private AliyunOss aliyunOss;

    @Tool("使用 Kroki 渲染 Mermaid 代码为 SVG 架构图")
    public List<ImageResource> generateArchitectureDiagram(@P("Mermaid 图表代码") String mermaidCode,
                                               @P("图描述") String description) {
        if (StrUtil.isBlank(mermaidCode)) {
            return Collections.emptyList();
        }
        try {
            byte[] svgBytes = renderMermaidByKrokiHutool(mermaidCode);
            if (svgBytes == null || svgBytes.length == 0) {
                throw new RuntimeException("Kroki 渲染结果为空");
            }

            // 上传到 OSS
            ByteArrayInputStream in = new ByteArrayInputStream(svgBytes);
            String key = String.format("kroki/mermaid/%s.svg", RandomUtil.randomString(8));
            String url = aliyunOss.upload(in, key);

            if (StrUtil.isNotBlank(url)) {
                ImageResource res = ImageResource.builder()
                        .category(ImageCategoryEnum.ARCHITECTURE)
                        .description(description)
                        .url(url)
                        .build();
                return Collections.singletonList(res);
            } else {
                log.error("OSS 上传返回 URL 为空");
            }
        } catch (Exception e) {
            log.error("用 Hutool 调用 Kroki 渲染失败", e);
        }
        return Collections.emptyList();
    }

    private byte[] renderMermaidByKrokiHutool(String mermaidCode) {
        String url = "http://localhost:8000/mermaid/svg";
        HttpRequest req = HttpRequest.post(url)
                .header("Accept", "image/svg+xml")
                .contentType("text/plain; charset=UTF-8")
                .body(mermaidCode)
                .timeout(120_000);
        try (HttpResponse resp = req.execute()) {
            if (resp.getStatus() != 200) {
                throw new HttpException("Kroki HTTP错误: " + resp.getStatus() + " → " + resp.body());
            }
            return resp.bodyBytes();
        }
    }

}
